package com.eipc;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.androidpn.sdk.Constants;
import org.androidpn.sdk.XmppManager;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.eipc.event.OnBarClickListener;
import com.eipc.event.OnFetchOtherFinishedListener;
import com.eipc.model.Game;
import com.eipc.model.News;
import com.eipc.model.Response;
import com.eipc.model.Weather;
import com.eipc.util.HttpManager;
import com.eipc.util.JsonParse;
import com.eipc.util.MyLog;

/**
 * 天气预报
 * @author x_liaolijun
 *
 * 2010-9-22 下午09:42:49
 *  
 * WeatherActivity
 *
 */
public class WeatherActivity extends CommonActivity {
	private Weather mWeather;
	private TextView mMessage;
	private TextView mLastUpdateTime;
	private TextView mCurWeather;
	private ImageView mCurImage;
	private ListView mDetailList;
	private ImageView mFeatureImageAM1;
	private TextView mFeatureTextAM1;
	private ImageView mFeatureImagePM1;
	private TextView mFeatureTextPM1;
	private ImageView mFeatureImageAM2;
	private TextView mFeatureTextAM2;
	private ImageView mFeatureImagePM2;
	private TextView mFeatureTextPM2;
	private String[] weathers;
	private ContentResolver mResolver ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weather);
		initView();
	}
	
	protected void initView(){
		super.initView();
		mBar.setOnRightClickListener(new View.OnClickListener(){		
			@Override
			public void onClick(View v) {
				new PollingWeatherTask().execute();
			}
		});
		mResolver = getContentResolver();
		mBar.setMiddleText(R.string.weather);
		mMessage = (TextView)findViewById(R.id.tv_info);
		mLastUpdateTime = (TextView)findViewById(R.id.tv_last_update_time);
		mCurImage = (ImageView)findViewById(R.id.iv_weather);
		mCurWeather = (TextView)findViewById(R.id.tv_today_weather);
		mDetailList = (ListView)findViewById(R.id.lv_today_detail_weather);
		mFeatureImageAM1 = (ImageView)findViewById(R.id.iv_am_weather1);
		mFeatureImageAM2 = (ImageView)findViewById(R.id.iv_am_weather2);
		mFeatureImagePM1 = (ImageView)findViewById(R.id.iv_pm_weather1);
		mFeatureImagePM2 = (ImageView)findViewById(R.id.iv_pm_weather2);
		mFeatureTextAM1 = (TextView)findViewById(R.id.tv_am_weather1);
		mFeatureTextAM2 = (TextView)findViewById(R.id.tv_am_weather2);
		mFeatureTextPM1 = (TextView)findViewById(R.id.tv_pm_weather1);
		mFeatureTextPM2 = (TextView)findViewById(R.id.tv_pm_weather2);
		
		weathers = mRe.getStringArray(R.array.weather);
		mWeather = mDB.queryWeather();
		updateView();
	}
	
	@Override
	protected void updateView(){
		super.updateView();
		if(mWeather!=null){
			if(mWeather.message!=null && !"".equals(mWeather.message)){
				mMessage.setText(mWeather.message);
			}
			else{
				mMessage.setVisibility(View.GONE);
			}
			mLastUpdateTime.setText(getString(R.string.weather_last_update_time,mWeather.updateTime));
			Calendar c = new GregorianCalendar();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			mCurImage.setImageResource(getWeatherImage(mWeather.currentStatus));
			mCurWeather.setText(getString(R.string.weather_today_temperature, getWeatherText(mWeather.currentStatus),mWeather.temperature));
			
			mDetailList.setAdapter(new ArrayAdapter<String>(this,R.layout.list_text, R.id.text1, buildAdapter(hour)));
			
			mFeatureImageAM1.setImageResource(getWeatherImage(mWeather.typeHalf1));
			mFeatureImagePM1.setImageResource(getWeatherImage(mWeather.typeHalf2));
			mFeatureImageAM2.setImageResource(getWeatherImage(mWeather.typeHalf3));
			mFeatureImagePM2.setImageResource(getWeatherImage(mWeather.typeHalf4));
			
			String[] cur = getFeatureDate();
			mFeatureTextAM1.setText(getString(R.string.am,cur[0],getWeatherText(mWeather.typeHalf1),doStatus(mWeather.statusHalf1)));
			mFeatureTextPM1.setText(getString(R.string.pm,cur[0],getWeatherText(mWeather.typeHalf2),doStatus(mWeather.statusHalf2)));
			mFeatureTextAM2.setText(getString(R.string.am,cur[1],getWeatherText(mWeather.typeHalf3),doStatus(mWeather.statusHalf3)));
			mFeatureTextPM2.setText(getString(R.string.pm,cur[1],getWeatherText(mWeather.typeHalf4),doStatus(mWeather.statusHalf4)));
		}
		else{
			mMessage.setVisibility(View.GONE);
		}
	}
	
	private ArrayList<String> buildAdapter(int hour){
		ArrayList<String> details = new ArrayList<String>();
		boolean flag = false;
		int i = 0;
		if(hour>=0 && hour<2){
			details.add(getString(R.string.hour, "0-2",getWeatherText(mWeather.typePeriod1),mWeather.statusPeriod1));
			flag = true;
			i++;
		}
		if((hour>=2 && hour<4) || flag){
			details.add(getString(R.string.hour, "2-4",getWeatherText(mWeather.typePeriod2),mWeather.statusPeriod2));
			flag = true;
			i++;
		}
		if((hour>=4 && hour<6) || flag){
			details.add(getString(R.string.hour, "4-6",getWeatherText(mWeather.typePeriod3),mWeather.statusPeriod3));
			flag = true;
			i++;
		}
		if((hour>=6 && hour<8) || flag){
			details.add(getString(R.string.hour, "6-8",getWeatherText(mWeather.typePeriod4),mWeather.statusPeriod4));
			flag = true;
			i++;
		}
		if((hour>=8 && hour<10) || flag){
			details.add(getString(R.string.hour, "8-10",getWeatherText(mWeather.typePeriod5),mWeather.statusPeriod5));
			flag = true;
			i++;
		}
		if((hour>=10 && hour<12) || flag){
			details.add(getString(R.string.hour, "10-12",getWeatherText(mWeather.typePeriod6),mWeather.statusPeriod6));
			flag = true;
			i++;
		}
		if((hour>=12 && hour<14) || flag){
			details.add(getString(R.string.hour, "12-14",getWeatherText(mWeather.typePeriod7),mWeather.statusPeriod7));
			flag = true;
			i++;
		}
		if((hour>=14 && hour<16) || flag){
			details.add(getString(R.string.hour, "14-16",getWeatherText(mWeather.typePeriod8),mWeather.statusPeriod8));
			flag = true;
			i++;
		}
		if((hour>=16 && hour<18) || flag){
			details.add(getString(R.string.hour, "16-18",getWeatherText(mWeather.typePeriod9),mWeather.statusPeriod9));
			flag = true;
			i++;
		}
		if((hour>=18 && hour<20) || flag){
			details.add(getString(R.string.hour, "18-20",getWeatherText(mWeather.typePeriod10),mWeather.statusPeriod10));
			flag = true;
			i++;
		}
		if((hour>=20 && hour<22) || flag){
			details.add(getString(R.string.hour, "20-22",getWeatherText(mWeather.typePeriod11),mWeather.statusPeriod11));
			flag = true;
			i++;
		}
		if((hour>=22 && hour<24) || flag){
			details.add(getString(R.string.hour, "22-24",getWeatherText(mWeather.typePeriod12),mWeather.statusPeriod12));
			flag = true;
			i++;
		}
		mDetailList.setLayoutParams(new LinearLayout.LayoutParams(-1, 41*i));
		return details;
	}
	
	/*
	 * 处理status字段存的时候，带有逗号分隔，而有些地方是分开的
	 */
	private String doStatus(String oStatus){
		return oStatus.replaceAll(",", "\n");
	}
	
	/*
	 * 得到未来二天的日期
	 */
	private String[] getFeatureDate(){
		Calendar c = new GregorianCalendar();
		c.add(Calendar.DATE, 1);
		String[] dates = new String[2];
		dates[0] = (c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DATE);
		
		c.add(Calendar.DATE, 1);
		dates[1] = (c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DATE);
		return dates;
	}
	
	/*
	 * 得到当前的天气
	 */
	private String[] getCurrentWeather(int hour){
		String[] text = new String[2];
		switch(hour){
			case 0:
			case 1:
				text[1] = mWeather.statusPeriod1;
				text[0] = mWeather.typePeriod1;
				break;
			case 2:
			case 3:
				text[1] = mWeather.statusPeriod2;
				text[0] = mWeather.typePeriod2;
				break;
			case 4:
			case 5:
				text[1] = mWeather.statusPeriod3;
				text[0] = mWeather.typePeriod3;
				break;
			case 6:
			case 7:
				text[1] = mWeather.statusPeriod4;
				text[0] = mWeather.typePeriod4;
				break;
			case 8:
			case 9:
				text[1] = mWeather.statusPeriod5;
				text[0] = mWeather.typePeriod5;
				break;
			case 10:
			case 11:
				text[1] = mWeather.statusPeriod6;
				text[0] = mWeather.typePeriod6;
				break;
			case 12:
			case 13:
				text[1] = mWeather.statusPeriod7;
				text[0] = mWeather.typePeriod7;
				break;
			case 14:
			case 15:
				text[1] = mWeather.statusPeriod8;
				text[0] = mWeather.typePeriod8;
				break;
			case 16:
			case 17:
				text[1] = mWeather.statusPeriod9;
				text[0] = mWeather.typePeriod9;
				break;
			case 18:
			case 19:
				text[1] = mWeather.statusPeriod10;
				text[0] = mWeather.typePeriod10;
				break;
			case 20:
			case 21:
				text[1] = mWeather.statusPeriod11;
				text[0] = mWeather.typePeriod11;
				break;
			case 22:
			case 23:
				text[1] = mWeather.statusPeriod12;
				text[0] = mWeather.typePeriod12;
				break;
		}
		return text;
	}
	
	/*
	 * 根据类型获取图片
	 */
	private int getWeatherImage(String type){
		int image = 0;
		image = mRe.getIdentifier("weather_"+(type.length()>1?type:"0"+type), "drawable", getPackageName());
		return image;
	}
	
	/*
	 * 根据类型天气文字
	 */
	private String getWeatherText(String type){
		int i = Integer.valueOf(type);
		if(i>0 && i<weathers.length) return weathers[Integer.valueOf(type)];
		return "";
	}
	
	class PollingWeatherTask extends CommonTask<Void>{
		public PollingWeatherTask(){
			super(WeatherActivity.this);
		}
		private String mResult;
		@Override
		protected Void doInBackground(Void... params) {
			Log.i("--"+this.getClass().getName(),"------------------polling weather------------------ right : ");
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
				String maxID = mDB.getCurrentDateVersion();
				String ids = "-1";
				mResult = HttpManager.polling(getString(R.string.url_polling),Constants.TTYPE_WEATHER,maxID,ids,mobileID,"0");
			} catch (Exception e) {
				MyLog.error(FetchConsultService.class,"",e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Response res;
			try{res = JsonParse.parseRespnse(mResult);}catch(Exception e){res = null;}
            if(XmppManager.isLogin&&res!=null&&res.success){
            	//TODO 刷新成功 等待 PUSH
            	mWeather = mDB.queryWeather();
				new FetchOtherTask(WeatherActivity.this, mDB, new OnFetchOtherFinishedListener() {	
					@Override
					public void OnFinished(ArrayList<News> news, Game game, Weather weather) {
						if(news!=null && news.size()>0){
							for(News n : news){
								mInfos.addView(getNewsView(n));
								mInfos.startFlipping();
							}
						}
						else{
							mInfos.addView( mInflater.inflate(R.layout.news_item, null));
						}
						mBottomBar.setGame(game);
						mBottomBar.setWeather(weather);
						mBottomBar.startFlipper();
					}
				}).execute(mLocale);
				updateView();
			}else{
				mBuilder.setMessage(R.string.status_connect_failed).setNegativeButton(R.string.btn_close, null).show();
				Log.e(this.getClass().getName()+" polling failure : ","mResult is null");
			}
			
		}
		
	}
}
